<template>
  <div class="app-container bg-grey">

    <div v-show="showSearch">
      
      <el-row :gutter="12" class="bg-fff bor-r-10 p20 mb20">
        <el-col :span="1.5" v-for="dict in agentType">
          <el-tag class="tagQueryBtn" :class="queryP.graphId == dict.value ? 'tagQueryBtnActive' : ''" type="info"
            @click="upQuery('graphId', dict.value)" color="rgba(0,0,0,0)"><span class="icon iconfont" :class="dict.icon"
              style="margin-right:5px;"></span><span style="position: relative;top:-2px;">{{ dict.label
              }}</span></el-tag>
        </el-col>
        <el-col :span="1.5" class="right">
          <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple"
            @click="handleDelete">删除</el-button>
        </el-col>
        <el-col :span="1.5" class="right">
          <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single"
            @click="handleUpdate">修改</el-button>
        </el-col>
        <el-col :span="1.5" class="right">
          <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
        </el-col>
      </el-row>

    </div>
    <div class="h45">
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </div>


    <el-row justify="center" :gutter="10" class="mb110">
      <el-checkbox-group v-model="ids">
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" v-for="(item, i) in agentList">
          <el-card shadow="hover" class="card-diy mb10">
            <el-checkbox :label="item.assistant_id" v-show="false" />
            <div @click="toggleCheckbox(item)">
              <div class="card-header">
                <div class="card-title" :class="item.checked ? 'card-checked' : ''">{{ item.name }}</div>
                <dict-tag class="right" :options="agentType" :value="item.graph_id" />
              </div>
              <div class="card-content">
                <div class="coll_name" v-if="item.config.configurable">关联数据：{{ item.config.configurable.collection_name
                  }}</div>
                <!-- <div class="user">归属用户：{{ item.config.configurable.user_id }}</div> -->
                <div class="id"><el-input :value="item.assistant_id" size="mini" class=""/></div>
              </div>
              <div class="card-bottom">
                <div class="v">v{{ item.version }}</div>
                <el-button v-if="item.graph_id == 'indexer'" size="mini" type="text" icon="el-icon-folder-opened"
                  @click="handleAddData(item)">设置数据</el-button>
                <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(item)">修改</el-button>
                <el-button v-if="item.graph_id == 'indexer'" size="mini" type="text" icon="el-icon-delete"
                  @click="handleDeleteAdd(item)">删除</el-button>
                <el-button v-else size="mini" type="text" icon="el-icon-delete"
                  @click="handleDelete(item)">删除</el-button>
                <!-- <el-button  size="mini" type="text"
                @click="handleGetSchemas(item)">获取默认配置</el-button> -->
              </div>
            </div>
          </el-card>
        </el-col>
      </el-checkbox-group>
    </el-row>

    <div class="bg-grey page-posi-div" v-show="total > 0">
      <div class="bg-fff bor-r-10 p10 pb20">
        <pagination :total="total" :pageSizes="[8, 12, 16, 24]" :page.sync="queryP.pageNum" :limit.sync="queryP.limit"
          @pagination="getList" />
      </div>
    </div>



    <!-- 添加或修改岗位对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="890px" append-to-body>
      <agent-form ref="agentForm" :initial-data="form" :is-dis="isDis" />
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加数据 -->
    <el-dialog :title="titleAdd" :visible.sync="openAdd" width="890px" append-to-body>
      <add-docs ref="addDataForm" :initial-data="formAdd" />
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitAddData">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>




  </div>
</template>

<script>
import langC from "@/api/wenda/langChain"
import AgentForm from './AgentForm.vue'
import AddDocs from './AddDocs.vue'

export default {
  name: "Post",
  components: {
    AgentForm, AddDocs
  },
  dicts: ['sys_normal_disable'],
  data() {
    return {
      agentType: [{ value: 'retrieval_graph', label: "Agent助手", icon: "icon-jiqiren", raw: { listClass: 'success' } }, { value: 'agent', label: "问答助手", icon: "icon-mn_xiaoxi1", raw: { listClass: 'primary' } }, { value: 'indexer', label: "向量数据库", raw: { listClass: 'warning' } }],

      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      names: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 岗位表格数据
      agentList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryP: {
        pageNum: 1,
        offset: 0,
        limit: 12,
        name: "",
        graphId: "retrieval_graph",
        metadata: {},
      },
      // 表单参数
      form: {},
      isDis: false,
      openAdd: false,
      formAdd: { assistantId: '', docsStr: "[]", streamMode: ["debug", "messages"] },
      titleAdd: '',
    };
  },

  created() {
    this.getList();
  },
  methods: {
    handleGetSchemas(item) {
      langC.agentGetSchemas(item.assistant_id).then(res => {
        console.log(res)
      })
    },
    // 通过点击 div 切换复选框状态
    toggleCheckbox(item) {

      item.checked = !item.checked;
      console.log(item)
      this.updateIdsArray(item);
    },
    updateIdsArray(item) {
      const index = this.ids.indexOf(item.assistant_id);
      if (item.checked) {
        if (index === -1) this.ids.push(item.assistant_id);
      } else {
        if (index !== -1) this.ids.splice(index, 1);
      }
      this.handleSelectionChange()
      console.log(this.ids)
    },
    upQuery(key, val) {
      this.queryP[key] = val
      this.getList();
    },
    upConfig(e) {
      if (e == 'retrieval_graph') {
        this.agentC = this.graphC
      } else if (e == "indexer") {
        this.agentC = this.indexerC
      }
    },
    /** 查询岗位列表 */
    getList() {
      this.cancel()

      this.loading = true;
      let q = { ...this.queryP }
      this.queryP.offset = (this.queryP.pageNum - 1) * this.queryP.limit
      // console.log(this.queryP)
      langC.agentList(this.queryP).then(res => {
        this.agentList = res
        this.loading = false;
      });
      q.limit = 999
      q.offset = 0
      langC.agentList(q).then(res => {
        this.total = res.length
      });
    },
    // 取消按钮
    cancel() {
      this.ids = [];
      this.handleSelectionChange()
      this.openAdd = false;
      this.open = false;
      this.isDis = !1
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {};
      this.formAdd = {}
      this.agentC = {}
      this.isDis = !1
      this.resetForm("form");
      this.resetForm("formAdd");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      //   this.queryP.offset = 10;
      console.log(this.queryP)
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange() {
      if (this.ids.length == 1) {
        this.assistant_id = this.ids[0]
      } else {
        this.assistant_id = ""
      }
      this.single = this.ids.length != 1
      this.multiple = !this.ids.length
    },
    /** 新增按钮操作 */
    handleAddData(row) {
      this.reset();
      // 添加新数据时，先删除原有数据库 collection_name
      
      if (!row.config.configurable) {
        this.$modal.msgError("数据库未配置")
        return false
      }
      
      this.formAdd = { assistantId: row.assistant_id, collection_name: row.config.configurable.collection_name, docsStr: '[]', streamMode: ["debug", "messages"] }
      this.openAdd = true;
      this.titleAdd = "添加文档";
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.isDis = !1
      this.title = "添加助手";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.assistant_id || this.assistant_id
      langC.agentGet(id).then(res => {
        console.log(res)
        this.agentC = res.config
        res.configStr = JSON.stringify(res.config)
        res.metadataStr = JSON.stringify(res.metadata)
        this.isDis = true
        this.form = res;
        console.log("传入数据：",res)
        this.open = true;
        this.title = "修改助手";
      });
    },
    async submitAddData() {
      const valid = await this.$refs.addDataForm.validateForm()
      if (!valid) return

      const formData = this.$refs.addDataForm.getFormData()
      let thread = await langC.threadCreate({
        "thread_id": "",
        "metadata": { graph_id: "indexer", assistantId: formData.assistantId, },
        "if_exists": "raise",
      })
      if (!thread) {
        this.$modal.msgError("创建会话失败")
        return false
      }
      try {
        if (formData.collection_name) {
          langC.delLangC(formData.collection_name);
        }

        const docsArr = JSON.parse(formData.docsStr)
        formData.assistant_id = formData.assistantId
        formData.stream_mode = formData.streamMode
        formData.input = { docs: docsArr }
        const res = await fetch("/langC/threads/" + thread.thread_id + "/runs/stream", {
          method: 'post',
          body: JSON.stringify(formData),
          responseType: 'srteam',
          headers: {
            'Content-Type': 'application/json',
          }
        })
        setTimeout(() => {
          console.log("submitAddData-res:", res);
        }, 3000);

        this.$modal.msgSuccess("新增成功");
        this.openAdd = false;
      } catch (error) {
        console.error("请求失败:", error);
        this.$modal.msgError("操作失败，请重试");
      }
    },
    /** 提交按钮 */
    async submitForm() {
      const valid = await this.$refs.agentForm.validateForm()
      if (!valid) return
      try {
        let formData = this.$refs.agentForm.getFormData()
        // if (formData.graph_id != 'agent') {
        //   console.log("submitForm-formData:", formData);
        //   formData.config = { configurable: formData.config.configurable }
        // } else {
        //   formData.config = JSON.parse(formData.config) // 只有agent才需要转换，其余都有对应的默认配置
        // }
        const payload = {
          ...formData,
          assistantId: formData.assistant_id,
          graphId: formData.graph_id
        }

        if (formData.assistant_id) {
          await langC.agentUpdate(formData.assistant_id, payload)
          this.$modal.msgSuccess("修改成功")
        } else {
          payload.ifExists = "raise"
          await langC.agentCreate(payload)
          this.$modal.msgSuccess("新增成功")
        }

        this.cancel()
        this.getList()
      } catch (error) {
        console.error("请求失败:", error);
        this.$modal.msgError("操作失败，请重试");
      }
    },
    /** 删除按钮操作 */
    async handleDeleteAdd(row) {
      // console.log(row.config.configurable.collection_name)
      console.log(row)
      let collname = row.config.configurable.collection_name
      let aa
      this.$modal.confirm('是否确认删除名称为"' + row.name + '"的数据项？').then(() => {
        aa = langC.delLangC(collname);
      }).then(() => {
        console.log("AAAAA:::::", aa)
        this.handleDelete(row);
      }).catch(() => { });
    },
    /** 删除按钮操作 */
    async handleDelete(row) {
      console.log(row)
      const names = this.ids.length ? '是否确认删除' + this.ids.length + '个数据项？' : '是否确认删除名称为"' + row.name + '"的数据项？'
      const id = row.assistant_id
      console.log(row)
      console.log(names)
      console.log(this.ids)

      this.$modal.confirm(names).then(() => {
        if (this.ids.length) {
          for (let i = 0; i < this.ids.length; i++) {
            console.log(this.ids[i])
            langC.agentDelete(this.ids[i]);
          }
          return true
        } else {

          langC.agentDelete(id);
        }
      }).then(() => {
        this.$modal.msgSuccess("删除成功");
        setTimeout(() => {
          this.getList();
        }, 1000);
      }).catch(() => {
        this.getList()
      });
    },
  }
};
</script>
